<?php
namespace App\Services;

use App\Models\Admin\OrderBaleModel;
use App\Models\Admin\OrderTempModel;
use App\Models\LogModel;
use App\Models\OrderLogsModel;
use App\Models\User\UserModel;
use App\Sdk\Pay\Alipay;
use DB;


/**
 * @deprecated
*/
class OrdersPayService
{
    /**
     * 支付宝支付
     */
    const play_alipay='alipay';


    /**
     * channels' => [ 'pc' => 1, 'm' => 2, 'app' => 3, 'miniapp' => 4 ],
     */

    /**
     * 创建支付宝订单号
     * @param $channel
     * @param $payMode
     * @param $uid
     * @param $params
     * @return array|bool
     * @throws \Exception
     */
    public function createaAipayTrade($channel, $payMode,$params)
    {
        if (!in_array($channel, ['web', 'm', 'app'])) {
            return ['status'=>false,'msg'=>'交易渠道错误'];
        }

        //支付方式，借记卡、信用卡、支付宝直接支付
        if (!in_array(strtolower($payMode), ['bankpay', 'creditcard', 'directpay'])) {
            return ['status'=>false,'msg'=>'交易方式错误'];
        }

        try {
            $alipayGateway = new Alipay($channel);
            $data = [
                'oid'          => $params['oid'] ?? 0,
                'out_trade_no' => $params['out_trade_no'] ?? '',  //支付宝交易号
                'subject'      => $params['subject'] ?? '',
                'total_fee'    => $params['money'] ?? 0, //交易费用
                'body'         => $params['body'] ?? '',//费用描述
                'paymode'      => $payMode,
                'account'      => $params['money'], //订单金额
            ];

            return $alipayGateway->createTrade($data, $params['notifyUrl'], $params['returnUrl']);

        } catch (\Exception $exception) {
            info($exception->getMessage());

            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 支付宝回调
     * @param $channel
     * @param $uid
     * @param $tradeData
     * @return bool
     * @throws \Exception
     */
    public function alipayReceive($channel,$tradeData)
    {
        try {
            $alipayGateway = new Alipay($channel);
            $verifyResult = $alipayGateway->completePurchase($tradeData);
            if (isset($verifyResult['trade_status'])) {
                if (isset($verifyResult['refund_status'])) {
                    //退款成功回调
                    if ($verifyResult['trade_status'] == 'TRADE_SUCCESS') {
                        //部分退款成功
                        return true;
                    } elseif ($verifyResult['trade_status'] == 'TRADE_CLOSED') {
                        //全部退款成功
                        return true;
                    } elseif ($verifyResult['trade_status'] == 'TRADE_FINISHED') {
                        //交易结束
                        return true;
                    }
                } else {
                    //支付成功回调
                    if ($verifyResult['trade_status'] == 'TRADE_SUCCESS') {

                        return true;

                    } elseif ($verifyResult['trade_status'] == 'TRADE_FINISHED') {
                        //todo 交易成功后3个月，交易结束，结束后不能操作退款
                        return true;
                    } elseif ($verifyResult['trade_status'] == 'TRADE_CLOSED') {
                        //todo 交易关闭
                        return null;
                    }
                }
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }



    /**@api
     *  订单成功的回调
     */
    public function alipayReceiveOrder($channel,$tradeData)
    {
        try {
            $alipayGateway = new Alipay($channel);
            $verifyResult = $alipayGateway->completePurchase($tradeData);
            LogModel::add("alipayReceiveOrder:".json_encode($verifyResult));
            if (isset($verifyResult['trade_status'])) {
                if ($verifyResult['trade_status'] == 'TRADE_SUCCESS') {
                    return true;
                }
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }


    /**
     * 抢单支付宝回调
     * @param $uid
     * @param $tradeData
     * @return bool
     */
    public function grapAlipay($channel,$tradeData)
    {
        LogModel::add("grapAlipay:".json_encode($tradeData));
        try {
            //根据单号查询信息
            $orderTemp = OrderTempModel::where('out_trade_no',$tradeData['out_trade_no'])->first();
            if(!$orderTemp){
                return false;
            }
            $orderTemp->status = OrderTempModel::status_wancheng;
            $orderTemp->play_status = OrderTempModel::play_status_zhifu;
            DB::beginTransaction();
            if($orderTemp->save()){

                /*
                $count=OrderBaleModel::where([
                    'id'=>$orderTemp['bale']
                ])->update(['status'=>OrderBaleModel::status_wancheng]);
                if($count!==1){
                    DB::rollback();
                    $this->error.='更新商品订单状态错误';
                    return false;
                }*/
                $orderbale=OrderBaleModel::where([
                    'id'=>$orderTemp['bale']
                ])->select('id','status')->first();
                if(!$orderbale){
                    DB::rollback();
                    $this->error.='更新商品订单状态错误,rderBale订单未找到';
                    return false;
                }else{
                    $orderbale->status=OrderBaleModel::status_wancheng;
                    if(!$orderbale->save()){
                        DB::rollback();
                        $this->error.='更新商品订单状态错误';
                    }
                }


                $insert = [
                    'uid'=>$orderTemp['fid'],
                    'order_temp_id'=>$orderTemp['id'],
                    'out_trade_no'=>$tradeData['out_trade_no'],
                    'trade_no'=>$tradeData['trade_no'],
                    'amount'=>$tradeData['price'],
                    'descri'=>$tradeData['body'],
                    'account'=>$tradeData['buyer_email'],
                    'addtime'=>time(),
                    'type'=>1,
                    'channel'=>$channel
                ];
                if(OrderLogsModel::insert($insert)){
                    //更新用户余额
                    //$user_mdl = new UserModel();
                    //if($user_mdl->where('id',$orderTemp['fid'])->increment('finance',$tradeData['price'])){
                        DB::commit();
                        return true;
                    //}else{
                       // DB::rollback();
                       // return false;
                   // }
                }else{
                    DB::rollback();
                    $this->error.='写入数据失败';
                    return false;
                }
            }else{
                $this->error.='更新数据失败';
            }
        }  catch (\Exception $e) {
            \Log::error($e->getMessage());
            DB::rollback();
            $this->error.=$e->getMessage();
            return false;
        }
    }
    public $error='';

    /**
     * 支付宝退款
     * @param $oid
     * @throws \Exception
     */
    public function alipayRefund($oid)
    {
        //根据OID查询订单详情
        $order = [];

        $out_trade_no = '2019052222001425431038446352';
        $amount = 0.01;

        $alipayGateway = new Alipay('refund');
        $result = $alipayGateway->refundNoPwd($out_trade_no, $amount);
        dd($result);
    }
    
    public function test(){
        echo "test()";
    }
}
